package org.jeecg.modules.sms.sms.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.lock.client.RedissonLockClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.sms.hyrApi.service.IHrySmsService;
import org.jeecg.modules.sms.sms.entity.CsSmsFsjl;
import org.jeecg.modules.sms.sms.param.SmsParam;
import org.jeecg.modules.sms.sms.service.ICsSmsCzjlService;
import org.jeecg.modules.sms.sms.service.ICsSmsFsjlService;
import org.jeecg.modules.sms.sms.service.ISmsService;
import org.jeecg.modules.sms.sms.util.SmsUtil;
import org.jeecg.modules.sms.sms.vo.SmsRtn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SmsServiceImpl implements ISmsService {
    private static final String lockKeyPrix = "sms_send_";
    @Autowired
    private IHrySmsService hrySmsService;

    @Autowired
    private ICsSmsFsjlService csSmsFsjlService;

    @Autowired
    private ICsSmsCzjlService csSmsCzjlService;

    @Autowired
    RedissonLockClient redissonLock;

    @Override
    public Result<SmsRtn> sendBatch(SmsParam sms) {
        String tenantId = TenantContext.getTenant();
        log.info("短信发送当前租户ID：" + tenantId);

        //整体按租户加锁
        String lockName = lockKeyPrix + tenantId;
        if(redissonLock.tryLock(lockName,30,20)){//单位秒
            try {
                //计算本次短信总条数，校验短信余额
                int oneSmsTs = SmsUtil.getDxts(sms.getMsg());
                int zts = sms.getPhone().split(",").length * oneSmsTs;
                boolean isValid = csSmsCzjlService.checkSmsYe(tenantId,zts);
                if(!isValid) {
                    return Result.error("短信余额不足");
                }
                Result<SmsRtn> result = hrySmsService.sendBatch(sms);

                if(result.isSuccess()) {
                    SmsRtn smsRtn = result.getResult();
                    int successCount = 0;
                    //保存发送记录等
                    List<CsSmsFsjl> csSmsFsjlList = new ArrayList<>();
                    for(SmsRtn.Fsjg fsjg : smsRtn.getFsjg()){
                        CsSmsFsjl csSmsFsjl = new CsSmsFsjl();
                        csSmsFsjl.setTenantId(Integer.parseInt(tenantId));
                        csSmsFsjl.setSjhm(fsjg.getPhone());
                        csSmsFsjl.setFsnr(sms.getMsg());
                        csSmsFsjl.setFssj(DateUtils.getDate());
                        if ("200".equals(fsjg.getCode())) {
                            csSmsFsjl.setSfcg("1");
                            csSmsFsjl.setSbyy("");
                            successCount ++;
                        } else {
                            csSmsFsjl.setSfcg("0");
                            csSmsFsjl.setSbyy(fsjg.getMsg());
                        }
                        csSmsFsjl.setUid(fsjg.getUid());
                        csSmsFsjl.setDxtdlx(smsRtn.getDxtdlx());
                        csSmsFsjl.setJfts(SmsUtil.getDxts(sms.getMsg()));
                        csSmsFsjlList.add(csSmsFsjl);
                    }
                    csSmsFsjlService.saveBatch(csSmsFsjlList);

                    //扣减余额数量
                    int successTotal = successCount * oneSmsTs;
                    csSmsCzjlService.reduceSmsYe(tenantId, successTotal);
                }
                return result;
            } finally {
                redissonLock.unlock(lockName);
            }
        } else {
            return Result.error("发送失败，请稍后重试");
        }
    }
}
